package archimede;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;

import net.miginfocom.swing.MigLayout;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;

public class ObjM extends JPanel {

  private JPanel photo = new JPanel();
  private ArrayList<tableM> values = new ArrayList<tableM>();
  private int count = 0;

  private JButton addRilevazione = new JButton(new ImageIcon(
      ClassLoader.getSystemResource("plus.png")));

  private JButton upload1 = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
  private JButton upload2 = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
  private JButton upload3 = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
  private JButton upload4 = new JButton(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
  private String lastPath = "";
  private String pathIm1 = "";
  private String pathIm2 = "";
  private String pathIm3 = "";
  private String pathIm4 = "";
  private String sourceIm1 = "";
  private String sourceIm2 = "";
  private String sourceIm3 = "";
  private String sourceIm4 = "";

  private String[] espItem = { "", "nord", "nord-est", "est", "sud-est", "sud", "sud-ovest",
      "ovest", "nord-ovest" };
  private JComboBox esposizione = new JComboBox(espItem);
  private String[] murItem = { "", "perimetrale interrata", "perimetrale fuori terra",
      "perimetrale parzialmente interrata", "intermedia interrata", "intermedia fuori terra",
      "intermedia parzialmente interrata", "altro" };
  private JComboBox mura = new JComboBox(murItem);
  private boolean modMura = false;
  private JTextField otherMura = new JTextField() {
    @Override
    protected void paintComponent(Graphics g) {
      if (!isOpaque()) {
        int w = getWidth();
        int h = getHeight();
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(UIManager.getColor("TextField.background"));
        g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
        g2.setColor(Color.BLACK);
        g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
        g2.dispose();
      }
      super.paintComponent(g);
    }
  };

  private JPanel rilievi = new JPanel();

  private JTextPane note = new JTextPane();

  private StartingWindow st;

  private int m;

  private String directoryProject;

  private JPanel espo = new JPanel();

  protected void paintComponent(Graphics g) {
    setOpaque(false);
    g.drawImage((new ImageIcon(ClassLoader.getSystemResource("sfondo.jpg"))).getImage(), 0, 0, null);
    super.paintComponent(g);
  }

  public ObjM(final StartingWindow st, final int m) {
    super();
    this.st = st;
    this.m = m;

    Properties pc = System.getProperties();
    String homePath = pc.getProperty("user.home");
    directoryProject = homePath + pc.getProperty("file.separator") + "ArchimedeSuper"
        + pc.getProperty("file.separator") + "aaAAzzZZ" + pc.getProperty("file.separator");

    lastPath = st.getPath();
    addRilevazione.setBorder(null);
    addRilevazione.setContentAreaFilled(false);
    addRilevazione.setRolloverEnabled(true);
    addRilevazione.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("plus_roll.png")));

    upload1.setBorder(null);
    upload1.setContentAreaFilled(false);
    upload1.setRolloverEnabled(true);
    upload1.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
    upload1.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        ImagePreviewPanel preview = new ImagePreviewPanel();
        chooser.setAccessory(preview);
        chooser.addPropertyChangeListener(preview);
        lastPath = st.getPath();
        if (lastPath.equals(""))
          chooser.getCurrentDirectory();
        else
          chooser.setCurrentDirectory(new File(lastPath));
        int returnValue = chooser.showOpenDialog(upload1);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
          String sourcePath = chooser.getSelectedFile().toString();
          st.setPath(sourcePath);
          lastPath = sourcePath;

          // indirizzo da dove prendere la foto
          sourceIm1 = sourcePath;
          ImageIcon tmp = new ImageIcon(sourcePath);
          // mostro la foto nella schemata java
          tmp.setImage(tmp.getImage().getScaledInstance(250, 200, Image.SCALE_AREA_AVERAGING));

          // file di destinazione
          String destPath = directoryProject + "1m" + m + "." + "jpg";
          pathIm1 = destPath;

          upload1.setIcon(tmp);
          st.refresh();
        }
      }
    });

    upload2.setBorder(null);
    upload2.setContentAreaFilled(false);
    upload2.setRolloverEnabled(true);
    upload2.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
    upload2.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        ImagePreviewPanel preview = new ImagePreviewPanel();
        chooser.setAccessory(preview);
        chooser.addPropertyChangeListener(preview);
        lastPath = st.getPath();
        if (lastPath.equals(""))
          chooser.getCurrentDirectory();
        else
          chooser.setCurrentDirectory(new File(lastPath));
        int returnValue = chooser.showOpenDialog(upload2);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
          String sourcePath = chooser.getSelectedFile().toString();
          st.setPath(sourcePath);
          lastPath = sourcePath;

          sourceIm2 = sourcePath;
          ImageIcon tmp = new ImageIcon(sourcePath);
          tmp.setImage(tmp.getImage().getScaledInstance(250, 200, Image.SCALE_AREA_AVERAGING));

          String destPath = directoryProject + "2m" + m + "." + "jpg";
          pathIm2 = destPath;

          upload2.setIcon(tmp);

          photo.add(upload3, "cell 2 0");
          photo.add(upload4, "cell 3 0");
          st.refresh();
        }
      }
    });

    upload3.setBorder(null);
    upload3.setContentAreaFilled(false);
    upload3.setRolloverEnabled(true);
    upload3.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
    upload3.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        ImagePreviewPanel preview = new ImagePreviewPanel();
        chooser.setAccessory(preview);
        chooser.addPropertyChangeListener(preview);
        lastPath = st.getPath();
        if (lastPath.equals(""))
          chooser.getCurrentDirectory();
        else
          chooser.setCurrentDirectory(new File(lastPath));
        int returnValue = chooser.showOpenDialog(upload3);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
          String sourcePath = chooser.getSelectedFile().toString();
          st.setPath(sourcePath);
          lastPath = sourcePath;

          sourceIm3 = sourcePath;
          ImageIcon tmp = new ImageIcon(sourcePath);
          tmp.setImage(tmp.getImage().getScaledInstance(250, 200, Image.SCALE_AREA_AVERAGING));

          String destPath = directoryProject + "3m" + m + "." + "jpg";
          pathIm3 = destPath;

          upload3.setIcon(tmp);
          st.refresh();
        }
      }
    });

    upload4.setBorder(null);
    upload4.setContentAreaFilled(false);
    upload4.setRolloverEnabled(true);
    upload4.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon.jpg")));
    upload4.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        ImagePreviewPanel preview = new ImagePreviewPanel();
        chooser.setAccessory(preview);
        chooser.addPropertyChangeListener(preview);
        lastPath = st.getPath();
        if (lastPath.equals(""))
          chooser.getCurrentDirectory();
        else
          chooser.setCurrentDirectory(new File(lastPath));
        int returnValue = chooser.showOpenDialog(upload4);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
          String sourcePath = chooser.getSelectedFile().toString();
          st.setPath(sourcePath);
          lastPath = sourcePath;

          sourceIm4 = sourcePath;
          ImageIcon tmp = new ImageIcon(sourcePath);
          tmp.setImage(tmp.getImage().getScaledInstance(250, 200, Image.SCALE_AREA_AVERAGING));

          String destPath = directoryProject + "4m" + m + "." + "jpg";
          pathIm4 = destPath;

          upload4.setIcon(tmp);

          st.refresh();
        }
      }
    });

    addRilevazione.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        values.add(new tableM(st, count, ObjM.this));
        rilievi.add(values.get(count), "cell 1 " + (3 + ++count) + " 7 1");
        // count++;
        if (count < 15)
          rilievi.add(addRilevazione, "cell 1 " + (4 + count));
        else
          rilievi.remove(addRilevazione);
        st.refresh();
      }
    });

    ClipboardPopupMenu psClip = ClipboardPopupMenu.installForComponent(note);
    psClip.addCopyFunction("Copia");
    psClip.addCutFunction("Taglia");
    psClip.addPasteFunction("Incolla");

    MouseAdapter ml1 = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
          int res = JOptionPane.showConfirmDialog(null, "Eliminare foto?", "Attenzione", 0);
          if (res == 0) {
            if (!pathIm2.equals("")) {
              // scalo i valori dell'immagine 2 nell'immagine 1
              pathIm1 = pathIm2.replace("2m", "1m");

              sourceIm1 = sourceIm2;
              upload1.setIcon(upload2.getIcon());

              if (!pathIm3.equals("")) {
                // scalo i valori dell'immagine 3 nell'immagine 2
                pathIm2 = pathIm3.replace("3m", "2m");
                sourceIm2 = sourceIm3;
                upload2.setIcon(upload3.getIcon());

                if (!pathIm4.equals("")) {
                  // scalo i valori dell'immagine 4 nell'immagine 3
                  pathIm3 = pathIm4.replace("4m", "3m");
                  sourceIm3 = sourceIm4;
                  upload3.setIcon(upload4.getIcon());
                  // resetto i valori dell'immagine 4
                  pathIm4 = "";
                  sourceIm4 = "";
                  upload4.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));

                } else {
                  // resetto i valori dell'immagine 3
                  upload3.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
                  pathIm3 = "";
                  sourceIm3 = "";
                }
              } else {
                // resetto i valori dell'immagine 2
                upload2.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
                pathIm2 = "";
                sourceIm2 = "";
                // tolgo possibilità di inserire 3 e 4
                try {
                  photo.remove(upload3);
                  photo.remove(upload4);
                } catch (Exception noRemove) {
                  System.out.println("no remove");
                }

              }
            } else {
              // resetto i valori dell'immagine 1
              pathIm1 = "";
              sourceIm1 = "";
              upload1.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
            }
            st.refresh();
          }
        }
      }
    };
    upload1.addMouseListener(ml1);

    MouseAdapter ml2 = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
          int res = JOptionPane.showConfirmDialog(null, "Eliminare foto?", "Attenzione", 0);
          if (res == 0) {

            if (!pathIm3.equals("")) {
              // scalo i valori dell'immagine 3 nell'immagine 2
              pathIm2 = pathIm3.replace("3m", "2m");
              sourceIm2 = sourceIm3;
              upload2.setIcon(upload3.getIcon());

              if (!pathIm4.equals("")) {
                // scalo i valori dell'immagine 4 nell'immagine 3
                pathIm3 = pathIm4.replace("4m", "3m");
                sourceIm3 = sourceIm4;
                // resetto i valori dell'immagine 4
                pathIm4 = "";
                sourceIm4 = "";
                upload3.setIcon(upload4.getIcon());
                upload4.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
              } else {
                // resetto i valori dell'immagine 3
                upload3.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
                pathIm3 = "";
                sourceIm3 = "";
              }
            } else {
              // resetto i valori dell'immagine 2
              upload2.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
              pathIm2 = "";
              sourceIm2 = "";
              // tolgo possibilità di inserire 3 e 4
              try {
                photo.remove(upload3);
                photo.remove(upload4);
              } catch (Exception noRemove) {
                System.out.println("no remove");
              }

            }
            st.refresh();
          }
        }
      }
    };
    upload2.addMouseListener(ml2);

    MouseAdapter ml3 = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
          int res = JOptionPane.showConfirmDialog(null, "Eliminare foto?", "Attenzione", 0);
          if (res == 0) {

            if (!pathIm4.equals("")) {
              // scalo i valori dell'immagine 4 nell'immagine 3
              pathIm3 = pathIm4.replace("4m", "3m");
              sourceIm3 = sourceIm4;
              // resetto i valori dell'immagine 4
              pathIm4 = "";
              sourceIm4 = "";
              upload3.setIcon(upload4.getIcon());
              upload4.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
            } else {
              upload3.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
              pathIm3 = "";
              sourceIm3 = "";
            }
            st.refresh();
          }

        }
      }
    };
    upload3.addMouseListener(ml3);

    MouseAdapter ml4 = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
          int res = JOptionPane.showConfirmDialog(null, "Eliminare foto?", "Attenzione", 0);
          if (res == 0) {
            upload4.setIcon(new ImageIcon(ClassLoader.getSystemResource("bupload.jpg")));
            pathIm4 = "";
            sourceIm4 = "";
            st.refresh();
          }

        }
      }
    };
    upload4.addMouseListener(ml4);

    photo.setLayout(new MigLayout());
    photo.setOpaque(false);
    photo.add(upload1, "cell 0 0");
    photo.add(upload2, "cell 1 0");

    rilievi.setLayout(new MigLayout());
    rilievi.setOpaque(false);

    RoundedPanel datiPrelievo = new RoundedPanel("Dati prelievo");
    datiPrelievo.setPreferredSize(new Dimension(283, 45));
    datiPrelievo.setOpaque(false);

    RoundedPanel altezza = new RoundedPanel("<html>Altezza dal<br>pavimento (cm)</html>");
    altezza.setPreferredSize(new Dimension(140, 45));
    altezza.setOpaque(false);

    RoundedPanel profondita = new RoundedPanel("<html>Profondità del<br>prelievo (cm)</html>");
    profondita.setPreferredSize(new Dimension(140, 45));
    profondita.setOpaque(false);

    RoundedPanel umidita = new RoundedPanel("Valore umidità %");
    umidita.setOpaque(false);
    umidita.setPreferredSize(new Dimension(160, 45));
    RoundedPanel criticita = new RoundedPanel("Criticita' valore");
    criticita.setOpaque(false);
    criticita.setPreferredSize(new Dimension(160, 45));
    RoundedPanel materiale = new RoundedPanel("<html><br>Materiale prelievo</html>");
    materiale.setOpaque(false);
    materiale.setPreferredSize(new Dimension(210, 92));
    RoundedPanel muratura = new RoundedPanel(
        "<html>Fuori terra<br>Muro intermedio<br>Contro terra</html>");
    muratura.setOpaque(false);
    muratura.setPreferredSize(new Dimension(210, 92));

    rilievi.setLayout(new MigLayout("", "[]1[]3[]3[]3[]", "[]1[]"));
    rilievi.add(datiPrelievo, "cell 2 1 2 1 , gapleft 15");
    rilievi.add(umidita, "cell 4 1");
    rilievi.add(criticita, "cell 4 2");
    rilievi.add(materiale, "cell 6 1 1 2");
    rilievi.add(muratura, "cell 7 1 1 2");
    rilievi.add(altezza, "cell 2 2 , gapleft 15");
    rilievi.add(profondita, "cell 3 2");
    rilievi.add(addRilevazione, "cell 0 3");

    note.setPreferredSize(new Dimension(400, 200));
    note.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    note.setFont(new Font("Arial", Font.PLAIN, 16));

    espo.setOpaque(false);
    espo.setLayout(new MigLayout());
    JLabel direzione = new JLabel("Esposizione a ");
    direzione.setFont(new Font("Arial", Font.PLAIN, 16));
    JLabel mu = new JLabel("Tipo muratura ");
    mu.setFont(new Font("Arial", Font.PLAIN, 16));
    otherMura.setBorder((BorderFactory.createEmptyBorder(4, 8, 4, 8)));
    otherMura.setPreferredSize(new Dimension(250, 25));
    otherMura.setOpaque(false);
    mura.setPreferredSize(new Dimension(250, 25));
    esposizione.setPreferredSize(new Dimension(120, 25));
    mura.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        if (((String) mura.getSelectedItem()).equals("altro")) {
          espo.remove(mura);
          modMura = true;
          espo.add(otherMura, "cell 3 0");
          paintAll(getGraphics());
        }

      }
    });

    MouseAdapter ml5 = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
          espo.remove(otherMura);
          mura.setSelectedIndex(0);
          espo.add(mura, "cell 3 0");
          modMura = false;

          paintAll(getGraphics());
        }
      }
    };
    otherMura.addMouseListener(ml5);

    espo.add(direzione, "cell 0 0");
    espo.add(esposizione, "cell 1 0");
    espo.add(mu, "cell 2 0");
    espo.add(mura, "cell 3 0");

    setLayout(new MigLayout());
    add(photo, "dock north, gapleft 15");
    add(espo, "dock north, gapleft 15");
    add(rilievi, "dock north, gapleft 15");
    add(note, "dock north, gapleft 15");

  }

  public void removeTabel(int line) {
    // System.out.println("line : " + line + " count : " + values.size());
    count--;
    // rilievi.remove(values[line]);
    rilievi.remove(values.get(line));
    values.remove(line);
    for (int i = line; i < count; i++) {
      rilievi.add(values.get(i), "cell 1 " + (4 + i) + " 7 1");
      values.get(i).setCount(i);
    }

    if (count < 15)
      rilievi.add(addRilevazione, "cell 1 " + (5 + count));
    else
      rilievi.remove(addRilevazione);

    st.refresh();
  }

  public void setCell(JComponent c) {
    c.setBorder(BorderFactory.createLineBorder(Color.GRAY));
    c.setFont(new Font("Arial", Font.PLAIN, 16));
    c.setPreferredSize(new Dimension(210, 45));
    c.setOpaque(true);
    c.setBackground(new Color(238, 131, 107));
  }

  public String print() {
    String print = "";
    print = print + "\n#" + count;
    print = print + "\n#" + pathIm1.replace("aaAAzzZZ", st.getProject());
    print = print + "\n#" + pathIm2.replace("aaAAzzZZ", st.getProject());
    print = print + "\n#" + pathIm3.replace("aaAAzzZZ", st.getProject());
    print = print + "\n#" + pathIm4.replace("aaAAzzZZ", st.getProject());
    print = print + "\n#" + esposizione.getSelectedIndex();
    if (modMura)
      print = print + "\n#" + otherMura.getText();
    else
      print = print + "\n#" + mura.getSelectedIndex();
    for (int i = 0; i < count; i++) {
      print = print + values.get(i).print();
    }
    print = print + "\n#NoteStart\n#" + note.getText() + "\n#NoteStop";
    print = print + "\n#ENDM";

    return print;
  }

  public void setElement(String data) {
    Scanner c = new Scanner(data);
    // c.nextLine();
    String prova = c.nextLine();
    count = Integer.parseInt(prova);

    sourceIm1 = c.nextLine().substring(1);
    if (sourceIm1.contains("1m")) {

      pathIm1 = directoryProject.replace("aaAAzzZZ", st.getProject()) + "1m" + m + "." + "jpg";
      sourceIm1 = pathIm1;

      try {
        File sourceimage = new File(pathIm1);
        Image image = ImageIO.read(sourceimage);
        upload1.setIcon(new ImageIcon(image));
        photo.add(upload2, "cell 1 0");

      } catch (IOException e) {
        e.printStackTrace();
      }

    } else
      sourceIm1 = "";

    sourceIm2 = c.nextLine().substring(1);
    if (sourceIm2.contains("2m")) {

      pathIm2 = directoryProject.replace("aaAAzzZZ", st.getProject()) + "2m" + m + "." + "jpg";
      sourceIm2 = pathIm2;
      File sourceimage = new File(pathIm2);
      Image image;
      try {
        image = ImageIO.read(sourceimage);
        upload2.setIcon(new ImageIcon(image));
        photo.add(upload3, "cell 2 0");
        photo.add(upload4, "cell 3 0");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    } else
      sourceIm2 = "";

    sourceIm3 = c.nextLine().substring(1);
    if (sourceIm3.contains("3m")) {
      pathIm3 = directoryProject.replace("aaAAzzZZ", st.getProject()) + "3m" + m + "." + "jpg";
      sourceIm3 = pathIm3;
      File sourceimage = new File(pathIm3);
      Image image;
      try {
        image = ImageIO.read(sourceimage);
        upload3.setIcon(new ImageIcon(image));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else
      sourceIm3 = "";
    sourceIm4 = c.nextLine().substring(1);
    if (sourceIm4.contains("4m")) {
      pathIm4 = directoryProject.replace("aaAAzzZZ", st.getProject()) + "4m" + m + "." + "jpg";
      sourceIm4 = pathIm4;
      File sourceimage = new File(pathIm4);
      Image image;
      try {
        image = ImageIO.read(sourceimage);
        upload4.setIcon(new ImageIcon(image));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else
      sourceIm4 = "";

    esposizione.setSelectedIndex(Integer.parseInt(c.nextLine().substring(1)));

    String tmp = c.nextLine().substring(1);
    try {
      mura.setSelectedIndex(Integer.parseInt(tmp));
    } catch (Exception e) {
      otherMura.setText(tmp);
      modMura = true;
      espo.remove(mura);
      espo.add(otherMura, "cell 3 0");
      paintAll(getGraphics());
    }

    tmp = c.nextLine();
    while (c.hasNextLine()) {
      tmp = tmp + "\n" + c.nextLine();
    }
    // System.out.println("MMMMMMM : "+tmp);
    Scanner scanValue = new Scanner(tmp);

    // System.out.println("###############"+tmp);
    for (int i = 0; i < count; i++) {
      values.add(new tableM(st, i, ObjM.this));

      String valueTable = scanValue.nextLine().substring(1);
      for (int j = 0; j < 7; j++) {
        valueTable = valueTable + "\n" + scanValue.nextLine().substring(1);
        // System.out.println("###############" + valueTable);
      }

      values.get(i).setElement(valueTable);
      rilievi.add(values.get(i), "cell 1 " + (3 + i) + " 7 1");
      rilievi.add(addRilevazione, "cell 1 " + (4 + i));

    }

    scanValue.nextLine().substring(1);
    tmp = scanValue.nextLine().substring(1);
    String premesse = "";
    for (int i = 1; i > 0;) {

      // System.out.println("^^^" + tmp);
      if (tmp.equalsIgnoreCase("#NoteStop")) {
        note.setText(premesse.substring(0, premesse.length() - 1));
        i = -1;
        break;
      }
      premesse = premesse + tmp + "\n";
      tmp = scanValue.nextLine();
    }

  }

  public void resize(File in, int w, int h, String formato, String out) throws IOException {
    Image newImg = ImageIO.read(in).getScaledInstance(w, h, Image.SCALE_SMOOTH);
    BufferedImage bim = new java.awt.image.BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    bim.createGraphics().drawImage(newImg, 0, 0, null);
    FileOutputStream fos = new FileOutputStream(out);
    ImageIO.write(bim, formato, fos);
    fos.close();
  }

  public boolean save() {

    boolean done = true;
    if (!sourceIm1.equals("") && !sourceIm1.equals(pathIm1))
      try {
        resize(new File(sourceIm1), 250, 200, "jpg", pathIm1.replace("aaAAzzZZ", st.getProject()));
      } catch (Exception e) {
        sourceIm1 = "";
        pathIm1 = "";
        upload1.setIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon_err.png")));
        done = false;
        e.printStackTrace();
      }
    if (!sourceIm2.equals("") && !sourceIm2.equals(pathIm2))
      try {
        resize(new File(sourceIm2), 250, 200, "jpg", pathIm2.replace("aaAAzzZZ", st.getProject()));
      } catch (Exception e) {
        sourceIm2 = "";
        pathIm2 = "";
        upload2.setIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon_err.png")));
        done = false;
        e.printStackTrace();
      }
    if (!sourceIm3.equals("") && !sourceIm3.equals(pathIm3))
      try {
        resize(new File(sourceIm3), 250, 200, "jpg", pathIm3.replace("aaAAzzZZ", st.getProject()));
      } catch (Exception e) {
        sourceIm3 = "";
        pathIm3 = "";
        upload3.setIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon_err.png")));
        done = false;
        e.printStackTrace();
      }
    if (!sourceIm4.equals("") && !sourceIm4.equals(pathIm4))
      try {
        resize(new File(sourceIm4), 250, 200, "jpg", pathIm4.replace("aaAAzzZZ", st.getProject()));
      } catch (Exception e) {
        sourceIm4 = "";
        pathIm4 = "";
        upload4.setIcon(new ImageIcon(ClassLoader.getSystemResource("upload_icon_err.png")));
        done = false;
        e.printStackTrace();
      }

    return done;

  }

  public Document pdf(Document doc, int n) {

    Paragraph dati;
    dati = new Paragraph("Punto M" + n, FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD));
    dati.setAlignment(Element.ALIGN_LEFT);
    dati.setSpacingAfter(5);
    dati.setSpacingBefore(15);
    try {
      doc.add(dati);
    } catch (DocumentException e2) {
      e2.printStackTrace();
    }

    int col = 0;

    if (!pathIm1.equals(""))
      col++;
    if (!pathIm2.equals(""))
      col++;
    if (!pathIm3.equals(""))
      col++;
    if (!pathIm4.equals(""))
      col++;

    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    if (!pathIm1.equals(""))
      try {
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(pathIm1.replace(
            "aaAAzzZZ", st.getProject()));
        img.setCompressionLevel(9);
        if (col < 2)
          img.scaleAbsolute(265f, 210f);
        else
          img.scaleAbsolute(250f, 175f);
        PdfPCell cos = new PdfPCell(img);
        cos.setHorizontalAlignment(Element.ALIGN_LEFT);
        cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cos.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cos);
      } catch (BadElementException e) {

        e.printStackTrace();
      } catch (MalformedURLException e) {

        e.printStackTrace();
      } catch (IOException e) {

        e.printStackTrace();
      }
    if (!pathIm2.equals(""))
      try {
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(pathIm2.replace(
            "aaAAzzZZ", st.getProject()));
        img.setCompressionLevel(9);
        if (col < 2)
          img.scaleAbsolute(265f, 210f);
        else
          img.scaleAbsolute(250f, 175f);
        PdfPCell cos = new PdfPCell(img);
        cos.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cos.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cos);
      } catch (BadElementException e) {

        e.printStackTrace();
      } catch (MalformedURLException e) {

        e.printStackTrace();
      } catch (IOException e) {

        e.printStackTrace();
      }
    if (!pathIm3.equals(""))
      try {
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(pathIm3.replace(
            "aaAAzzZZ", st.getProject()));
        img.setCompressionLevel(9);
        dati = new Paragraph("");
        PdfPCell space = new PdfPCell(dati);
        space.setBorder(PdfPCell.NO_BORDER);
        table.addCell(space);
        table.addCell(space);
        if (col < 2)
          img.scaleAbsolute(265f, 210f);
        else
          img.scaleAbsolute(250f, 175f);
        PdfPCell cos = new PdfPCell(img);
        cos.setHorizontalAlignment(Element.ALIGN_LEFT);
        cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cos.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cos);
      } catch (BadElementException e) {

        e.printStackTrace();
      } catch (MalformedURLException e) {

        e.printStackTrace();
      } catch (IOException e) {

        e.printStackTrace();
      }
    if (!pathIm4.equals(""))
      try {
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(pathIm4.replace(
            "aaAAzzZZ", st.getProject()));
        img.setCompressionLevel(9);
        if (col < 2)
          img.scaleAbsolute(265f, 210f);
        else
          img.scaleAbsolute(250f, 175f);
        PdfPCell cos = new PdfPCell(img);
        cos.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cos.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cos);
      } catch (BadElementException e) {

        e.printStackTrace();
      } catch (MalformedURLException e) {

        e.printStackTrace();
      } catch (IOException e) {

        e.printStackTrace();
      }

    try {
      table.setSpacingAfter(5);
      doc.add(table);
    } catch (DocumentException e) {

      e.printStackTrace();
    }

    Phrase testo;
    if (modMura)
      testo = new Phrase("Esposizione a " + esposizione.getSelectedItem() + "    Tipo muratura "
          + otherMura.getText(), FontFactory.getFont(FontFactory.TIMES, 12));
    else
      testo = new Phrase("Esposizione a " + esposizione.getSelectedItem() + "    Tipo muratura "
          + mura.getSelectedItem(), FontFactory.getFont(FontFactory.TIMES, 12));
    Paragraph p = new Paragraph(testo);
    try {
      p.setSpacingBefore(5);
      p.setSpacingAfter(5);
      doc.add(p);
    } catch (DocumentException e) {

      e.printStackTrace();
    }

    table = new PdfPTable(8);
    int[] size = { 25, 30, 30, 20, 50, 5, 60, 60 };
    try {
      table.setWidths(size);
      table.setWidthPercentage(100);
    } catch (DocumentException e1) {

      e1.printStackTrace();
    }

    testo = new Phrase("Punti di prelievo", FontFactory.getFont(FontFactory.TIMES, 11, Font.BOLD));
    PdfPCell cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    // cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cos.setRowspan(2);
    cos.setFixedHeight(22);
    table.addCell(cos);

    testo = new Phrase("Dati del prelievo", FontFactory.getFont(FontFactory.TIMES, 11, Font.BOLD));
    cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cos.setFixedHeight(15);
    cos.setColspan(2);
    table.addCell(cos);

    testo = new Phrase("Valore umidita' in % in base al peso del materiale", FontFactory.getFont(
        FontFactory.TIMES, 11, Font.BOLD));
    cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    // cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cos.setFixedHeight(22);
    cos.disableBorderSide(2);
    cos.setColspan(3);
    cos.setRowspan(2);
    table.addCell(cos);

    testo = new Phrase("Materiale del prelievo", FontFactory.getFont(FontFactory.TIMES, 11,
        Font.BOLD));
    cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    cos.setFixedHeight(22);
    cos.setRowspan(2);
    table.addCell(cos);

    testo = new Phrase("Fuori terra\nContro terra\nMuro intermedio", FontFactory.getFont(
        FontFactory.TIMES, 11, Font.BOLD));
    cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    cos.setVerticalAlignment(Element.ALIGN_TOP);
    cos.setFixedHeight(22);
    cos.setRowspan(2);
    table.addCell(cos);

    testo = new Phrase("Altezza dal pavimento",
        FontFactory.getFont(FontFactory.TIMES, 8, Font.BOLD));
    cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cos.setFixedHeight(22);
    table.addCell(cos);

    testo = new Phrase("Profondita' del prelievo", FontFactory.getFont(FontFactory.TIMES, 8,
        Font.BOLD));
    cos = new PdfPCell(testo);
    cos.setHorizontalAlignment(Element.ALIGN_CENTER);
    cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cos.setFixedHeight(22);
    table.addCell(cos);

    try {

      doc.add(table);
    } catch (DocumentException e) {
      e.printStackTrace();
    }

    for (int i = 0; i < count; i++) {
      values.get(i).pdf(doc, n, i + 1);
    }

    if (!note.getText().equals("")) {
      table = new PdfPTable(1);
      table.setWidthPercentage(100);
      table.setKeepTogether(true);

      testo = new Phrase("Note M" + n, FontFactory.getFont(FontFactory.TIMES, 12, Font.BOLD));
      cos = new PdfPCell(testo);
      cos.setBorder(0);
      cos.setHorizontalAlignment(Element.ALIGN_LEFT);
      table.addCell(cos);

      testo = new Phrase(note.getText(), FontFactory.getFont(FontFactory.TIMES, 12));
      cos = new PdfPCell(testo);
      cos.setBorder(0);
      cos.setHorizontalAlignment(Element.ALIGN_LEFT);
      table.addCell(cos);

      try {
        table.setSpacingBefore(10);
        doc.add(table);
      } catch (DocumentException e) {
        e.printStackTrace();
      }

    }
    return doc;
  }

  public void replace(String newName, String oldName) {
    sourceIm1 = pathIm1;
    sourceIm2 = pathIm2;
    sourceIm3 = pathIm3;
    sourceIm4 = pathIm4;
    pathIm1 = pathIm1.replace(oldName, "aaAAzzZZ");
    pathIm2 = pathIm2.replace(oldName, "aaAAzzZZ");
    pathIm3 = pathIm3.replace(oldName, "aaAAzzZZ");
    pathIm4 = pathIm4.replace(oldName, "aaAAzzZZ");
  }

  public void changeM(int newM) {
    pathIm1 = pathIm1.replace("1m" + m, "1m" + newM);
    pathIm2 = pathIm2.replace("2m" + m, "2m" + newM);
    pathIm3 = pathIm3.replace("3m" + m, "3m" + newM);
    pathIm4 = pathIm4.replace("4m" + m, "4m" + newM);
    m = newM;
  }

  public int getM() {
    return m;
  }
}
